<template>
  <el-form class="BaseForm" ref="form" :model="prompt" label-width="88px" label-position="top">
    <div class="formContent">
      <div class="formTitle">基础图片</div>
      <el-form-item class="formItem">
        <ImagePicker TipsTxt="请上传需要替换模特的图片" ToPlatform="No-ComfyUI" @change="ChangeModelImg"  :DefaultImageUrl="imageUrl"></ImagePicker>
      </el-form-item>
      <div class="formTitle">基础描述</div>
      <el-form-item class="formItem">
        <!-- <el-input v-model="prompt.txt" type="textarea" :placeholder="promptTips()" rows="6"></el-input> -->
        <LilithChat v-model:text="prompt.txt" :placeholder="promptTips()" rows="6" :robot="true" />
      </el-form-item>
      <el-form-item class="formItem">
      <el-tabs class="formTab" v-if="promptSetting!=null" v-model="nowTab" @tab-click="changePromptTab" lazy="true" v-loading="isLoadingPrompt">
        <el-tab-pane v-for="(tab, index) in promptSetting.tabList" :label="tab.title" :name="tab.tabId">
          <PromptSession v-if="tab.tabId == nowTab" v-for="( session, index ) in tab.sessionGroup" 
          :key="index" 
          :Session="promptSetting.groupList.filter(ses=>ses.groupId == session)[0]" 
          :SelecterList="promptSetting.sessionList"
          @change="sessionDataChange"></PromptSession>
        </el-tab-pane>
      </el-tabs>
      </el-form-item>
    </div>
    <div class="formBottomBar">
      <div class="content">
        <div class="tips">描述建议<br />图片主体 + 环境背景 + 图片风格</div>
      </div>
      <el-button round class="FormBtn" @click="onSubmit" v-loading="nowLoading"><el-icon class="icon"><Brush /></el-icon><span class="txt">生成图片</span></el-button>
    </div>
  </el-form>
</template>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
<style>
</style>
<script>
import WebRequest from '../../unit/request.js'
import PromptSession from '../element/PromptSession.vue'
import ImagePicker from '../element/ImagePicker.vue'
import LilithChat from '../element/LilithChat.vue'
import OS from '../../unit/OS.js'
export default {
  name: 'ReplaceBackground',
  components: { PromptSession,ImagePicker,LilithChat },
  props: {
    src: '',
    title: '',
    date: '',
    imageUrl: '',
    sourceImageDepotId:''
  },
  data () {
    return {
      prompt: {
        txt: '',
        sessionData: []
      },
      promptSetting: null,
      isLoadingPrompt: false,
      nowTab: '',
      nowLoading:false,
      sourceImageDepotIdVal:'',
      baseImage:'',
    }
  },
  mounted(){
    if(this.promptSetting == null && !this.isLoadingPrompt)
    this.isLoadingPrompt = true
    WebRequest.GetSelecterSetting({
      callback: (res) => {
        if(res.status == 200 && res.data.errCode == 10000){
          this.promptSetting = JSON.parse(res.data.data)
          this.nowTab = this.promptSetting.tabList[0].tabId
          console.log(this.promptSetting)
          this.isLoadingPrompt = false
        }else{
          this.promptSetting = null
          this.isLoadingPrompt = false
        }
      }
    })
  },
  methods: {  
    getPromptData(){
      var tabData = this.promptSetting.tabList.filter(tab => tab.tabId == this.nowTab);
      var ApiData = {
        basePrompt: this.prompt.txt,
        optionPrompt: '',
        tabId:this.nowTab,
        tabName:tabData[0].title,
        promptList:'',
        promptValue:'',
        originalImage:this.baseImage
      }
      var promptTxt = ''
      var parmTxt = ''
      var promptListObj = [];
      var promptValueObj = [];
      if(tabData.length > 0){
        promptTxt = tabData[0].basePrompt
        parmTxt = tabData[0].baseParm
      }
      this.prompt.sessionData.forEach(ses=>{
        if(ses.data.length > 0){
          var groupObj = {
            groupId: ses.groupId,
            title: ses.title,
            desc: ses.desc,
            includeSelecter:[]
          }
          ses.data.forEach(sel=>{
            var selecterObj = {
              selecterId: sel.selecterId,
              selOptionVal: sel.promptTxt,
              selOptionName: sel.optionName,
              selOptionId: sel.optionId
            }
            groupObj.includeSelecter.push(selecterObj);
            promptValueObj.push(sel.optionName)
            if(sel.promptType == 'prompt'){
              promptTxt = promptTxt == ''?sel.promptTxt:promptTxt+', '+ sel.promptTxt
            }else{
              parmTxt = parmTxt == ''?sel.promptTxt:parmTxt+' '+ sel.promptTxt
            }
          })
          promptListObj.push(groupObj);
        }
      })
      ApiData.optionPrompt = promptTxt == ''?(parmTxt==''?'':parmTxt):(parmTxt==''?promptTxt:promptTxt + " " + parmTxt)
      ApiData.promptList = promptListObj
      ApiData.promptValue = promptValueObj
      console.log(ApiData);
      return ApiData;
    },
    onSubmit(e){
      this.nowLoading = true;
      WebRequest.PreConsumerPoint({
        serviceType:10,
        callback: (res) => {
          console.log(res);
          if(res.data.errCode == 10000){
            var coseId = res.data.data.id;
            this.$emit('startGenerate');
            console.log(this.prompt)
            var prompt = this.getPromptData()
            var extend = OS.GetFormSetting({
              operationId: "10",
              operationName: '换背景',
              describe: prompt.basePrompt,
              tabId:prompt.tabId,
              tabName:prompt.tabName,
              promptList:prompt.promptList,
              promptValue:prompt.promptValue,
              originalImage:prompt.originalImage,
            })
            var sourceImageDepotId = this.sourceImageDepotId//this.sourceImageDepotIdVal
            if(this.sourceImageDepotIdVal != '' && this.sourceImageDepotIdVal != null){
              sourceImageDepotId = this.sourceImageDepotIdVal
            }
            WebRequest.ReplaceBackground({
              costId:coseId,
              imgUrl:this.baseImage,
              basePrompt:prompt.basePrompt,
              optionPrompt:prompt.optionPrompt,
              extendValue: extend,
              sourceImageDepotId: sourceImageDepotId,
              callback:(e) => {
                if(e.data.errCode == 10000){
                  var resultImgUrl = e.data.data.imgUrl
                  this.$emit('ResultCalled',resultImgUrl)
                  this.nowLoading = false
                  /*WebRequest.SaveToLibrary({
                    tool: 10,
                    imageURL: resultImgUrl,
                    callback: (_e) => {
                      this.nowLoading = false
                      if(e.data.errCode == 10000){
                      }else{
                        console.log('保存图库失败',e)
                      }
                    },
                    error: (_e) => {
                      this.nowLoading = false
                      console.log('保存图库接口请求异常',e)
                    }
                  })*/
                }else{
                      this.nowLoading = false
                  console.log('请求生图失败',e)
                }
              },
              error: (e) => {
                this.nowLoading = false
                console.log('请求生图接口请求异常',e)
              }
            })
          }else{
            this.nowLoading = false
            console.log('扣费失败',res)
          }
        },
        error: (e) => {
            this.nowLoading = false
            console.log('扣费接口请求异常',res)
        }
      })
    },
    promptTips () {
      var tips = [
        '例：一个穿着白色长裙的漂亮女孩，站在咖啡店门口，枫叶在飘落，日落，电影风格',
        '例：一个美丽的上海女人，特写，王家卫电影风格',
        '例：一个可爱的小女孩在吃着雪糕，背景是儿童乐园，由彩色的气球，皮克斯动画风格',
        '例：夜晚的酒吧街，两边是冷光的霓虹灯，一对情侣牵手走在路上。'
      ]
      var random = Math.floor(Math.random() * tips.length)
      if (random >= tips.length) {
        random = 0
      }
      return tips[random]
    },
    changePromptTab(e){
      console.log(e)
    },
    sessionDataChange(e){
      var newSession = true;
      for(var i = 0; i< this.prompt.sessionData.length; i++){
        if(this.prompt.sessionData[i].groupId == e.groupId){
          this.prompt.sessionData[i] = JSON.parse(JSON.stringify(e));
          newSession = false;
        }
      }
      if(newSession){
        this.prompt.sessionData.push(e);
      }
    },
    ChangeModelImg (e) {
      console.log(e);
      if(e.fileName && e.fileName != null && e.fileName != ''){
        this.baseImage = e.fileName
      }else{
        this.baseImage = e.imageUrl
      }
      this.sourceImageDepotIdVal = e.sourceImageDepotId
    }
  }
}
</script>
